//
//  MDHRippleAnimationImageView.swift
//  JSTech
//
//  Created by 高得华 on 2019/8/4.
//  Copyright © 2020 华&梅. All rights reserved.
//

import UIKit

open class MDHRippleAnimationImageView: UIView {

    //MARK: - ==== 属性
    ///动画的layer
    fileprivate var _animationLayer: CALayer?
    ///是否在执行动画中
    fileprivate var _isAnimating = false
    ///动画组
    fileprivate var  _animationGroup: CAAnimationGroup?
    ///当前的图片
    @objc open lazy var imageView: UIImageView = {
        let imv = SDAnimatedImageView()
        self.addSubview(imv)
        return imv
    }()
    ///cornerRadius///圆角
    @objc public var radiusCorner: CGFloat = 0
    ///总共有多少个圈
    @objc public var countPulsing = 5
    ///圈的颜色
    @objc public var colorRadius = kColor_MDHHex("#35A4FF")
    // 设置 animationDuration ，表示动画时间
    @objc public var animationDuration: Double = 4
    // multiple
    @objc public var multiple: Double = 1.4
    
    override open func layoutSubviews() {
        super.layoutSubviews()
        self.imageView.frame = self.bounds
        self.imageView.dh_cornerRadius = self.radiusCorner
    }
    
    //open override func draw(_ rect: CGRect) {
    //    self.drawRectLayer(rect)
    //}
    
    ///
    fileprivate func drawRectLayer(_ rect: CGRect) -> () {
        let animationLayer = CALayer()
        for i in 0..<countPulsing {
            // 这里同时创建[缩放动画、背景色渐变、边框色渐变]三个简单动画
            let animationArray = self.animationArray()
            // 将三个动画合并为一个动画组
            let animationGroup = self.animationGroupAnimations(array: animationArray, index: i)
            //修改方法，将原先添加的动画由“简单动画”改为“动画组”
            let pulsingLayer = self.pulsingLayer(rect: rect, animationGroup: animationGroup)
            //将动画 Layer 添加到 animationLayer
            animationLayer.addSublayer(pulsingLayer)
        }
        _animationLayer = animationLayer
        self.layer.addSublayer(animationLayer)
    }
    
    fileprivate func pulsingLayer(rect: CGRect, animationGroup: CAAnimationGroup) -> CALayer {
        let pulsingLayer = CALayer()
        //    pulsingLayer.borderWidth = 0.5;
        //    pulsingLayer.borderColor = QFC_RColor(9,209,90, 0.5).CGColor;
        pulsingLayer.frame = CGRect(x: 0, y: 0, width: rect.width, height: rect.height)
        pulsingLayer.cornerRadius = self.radiusCorner
        pulsingLayer.add(animationGroup, forKey: "plulsing")
        return pulsingLayer
    }
    
    ///
    func animationGroupAnimations(array: [CAPropertyAnimation], index: Int) -> CAAnimationGroup {
        let animationGroup = CAAnimationGroup()
        animationGroup.beginTime = CACurrentMediaTime()+Double(index)*self.animationDuration/Double(self.countPulsing)
        animationGroup.duration = self.animationDuration
        animationGroup.repeatCount = MAXFLOAT
        animationGroup.animations = array
        animationGroup.isRemovedOnCompletion = false
        animationGroup.timingFunction = CAMediaTimingFunction.init(name: CAMediaTimingFunctionName.default)
        return animationGroup
    }
    
    ///
    fileprivate func animationArray() -> [CAPropertyAnimation] {
        let scaleAnimation = self.scaleAnimation()
        let borderColorAnimation = self.borderColorAnimation()
        let backgroundColorAnimation = self.backgroundColorAnimation()
        return [scaleAnimation, borderColorAnimation, backgroundColorAnimation]
    }
    
    // 使用关键帧动画，使得颜色动画不要那么的线性变化
    fileprivate func backgroundColorAnimation() -> CAKeyframeAnimation {
        return self.keyframeAnimation()
    }
    
    fileprivate func borderColorAnimation() -> CAKeyframeAnimation {
        return self.keyframeAnimation(keyPath: "borderColor")
    }
    fileprivate func keyframeAnimation(keyPath: String = "backgroundColor") -> CAKeyframeAnimation {
        let backgroundColorAnimation = CAKeyframeAnimation()
        backgroundColorAnimation.keyPath = keyPath;//9, 209, 90  //255, 216, 87 // 255, 231, 152 // 255, 241, 197
        
        var values = [CGColor]()
        var keyTimes = [NSNumber]()
        var alpha: CGFloat = 0.45//CGFloat(self.countPulsing)/8
        var kt_p: Double = 0.3
        for _ in 0..<self.countPulsing {
            kt_p += 0.3
            keyTimes.append(NSNumber.init(value: kt_p >= 1 ? kt_p-0.1:kt_p))
            values.append(self.colorRadius.withAlphaComponent(alpha).cgColor)
            alpha -= 0.15
        }
        backgroundColorAnimation.values = values
        backgroundColorAnimation.keyTimes = keyTimes
        return backgroundColorAnimation
    }
    
    fileprivate func scaleAnimation() -> CABasicAnimation {
        let scaleAnimation = CABasicAnimation.init(keyPath: "transform.scale")
        scaleAnimation.fromValue = 1
        scaleAnimation.toValue = self.multiple;
        //scaleAnimation.beginTime = CACurrentMediaTime();
        //scaleAnimation.duration = 3;
        //scaleAnimation.repeatCount = HUGE;// 重复次数设置为无限
        return scaleAnimation
    }
}

extension MDHRippleAnimationImageView {
    ///开始动画
    @objc open func startCustomAnimation() -> () {
        if _isAnimating {
            return
        }
        /*let animationLayer = CALayer()
        let pulsingLayers = self.setupAnimationLayers(rect: self.frame)
        for layer in pulsingLayers {
            animationLayer.addSublayer(layer)
        }
        self.layer.addSublayer(animationLayer)
        _animationLayer = animationLayer*/
        self.drawRectLayer(self.frame)
        _isAnimating = true
    }
    
    ///结束动画
    @objc open func stopCustomAnimation() -> () {
        if _isAnimating {
            let pulsingLayers = _animationLayer?.sublayers ?? [CALayer]()
            for layer in pulsingLayers {
                layer.removeAllAnimations()
                layer.removeFromSuperlayer()
            }
            _animationLayer?.removeAllAnimations()
            _animationLayer?.removeFromSuperlayer()
            _animationLayer = nil
            _isAnimating = false
        }
    }
    
    ///创建动画
    fileprivate func setupAnimationLayers(rect: CGRect) -> [CALayer] {
        var ret = [CALayer]()
        ///一次多少圈 的 layer
        let pulsingCount = self.countPulsing
        ///一圈d执行动画时间
        let animationDuration: Double = 3
        for i in 0..<pulsingCount {
            let pulsingLayer = CALayer()
            pulsingLayer.frame = CGRect.init(x: 0, y: 0, width: rect.width, height: rect.height)
            pulsingLayer.borderColor = self.colorRadius.cgColor
            pulsingLayer.borderWidth = 2
            pulsingLayer.cornerRadius = self.radiusCorner//8//rect.height/2.0
            
            ///
            let defaultCurve = CAMediaTimingFunction(name: CAMediaTimingFunctionName.default)
            
            let animationGroup = CAAnimationGroup()
            animationGroup.fillMode = CAMediaTimingFillMode.backwards
            animationGroup.beginTime = CACurrentMediaTime()+Double(i)*animationDuration/Double(pulsingCount)
            animationGroup.duration = animationDuration
            animationGroup.repeatCount = HUGE
            animationGroup.timingFunction = defaultCurve
            
            let scaleAnimation = CABasicAnimation.init(keyPath: "transform.scale")
            scaleAnimation.fromValue = 1.0
            scaleAnimation.toValue   = 1.36
            
            var oaValues = [NSNumber]()
            var oaTimes  = [NSNumber]()
            let count = pulsingCount*2
            for i in 0...count {
                let value = Float(i/count)
                oaValues.append(NSNumber.init(value: 1-value))
                oaTimes.append(NSNumber.init(value: value))
            }
            let opacityAnimation = CAKeyframeAnimation.init(keyPath: "opacity")
            opacityAnimation.values = oaValues
            opacityAnimation.keyTimes = oaTimes
            
            animationGroup.animations = [scaleAnimation, opacityAnimation]
            pulsingLayer.add(animationGroup, forKey: "plulsing")
            
            ret.append(pulsingLayer)
        }
        return ret
    }
}
